package com.zcc.makingfriend.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.zcc.makingfriend.dao.User;
import com.zcc.makingfriend.dao.WxLogin;
import com.zcc.makingfriend.mapper.UserMapper;
import com.zcc.makingfriend.mapper.WxLoginMapper;
import com.zcc.makingfriend.service.LoginService;
import com.zcc.makingfriend.service.WxLoginService;
import com.zcc.makingfriend.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author xiaomi
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxLoginMapper wxLoginMapper;

    @Override
    public Result wxLogin(String code) {
        JSONObject jsonObject = toJson(code);
        String openid = (String) jsonObject.get("openid");
        String session_key = (String)jsonObject.get("session_key");
        WxLogin wLogin = wxLoginMapper.findWxLogin(openid);
        if (wLogin != null) {
            String uuid = wLogin.getUuid();
            User userByUuid = userMapper.findUserByUuid(uuid);
            return Result.success(200, "登录成功", userByUuid);
        }
        // 通过UUID生成唯一的键
        String uuid = UUID.randomUUID().toString();

        WxLogin wxLogin = new WxLogin();
        wxLogin.setSessionKey(session_key);
        wxLogin.setOpenid(openid);
        wxLogin.setUuid(uuid);
        int i = wxLoginMapper.addWxLogin(wxLogin);

        if (i == 1) {
            // 微信登录就相当于注册了一个用户信息
            // 默认用户头像
            String avatar = "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132";
            // 默认用户昵称
            String username = "微信用户";
            // 注册时间
            LocalDateTime created = LocalDateTime.now();

            User user = new User();
            user.setUuid(uuid);
            user.setUsername(username);
            user.setAvatar(avatar);
            // 0表示未注销，1表示注销
            user.setStatus(0);
            user.setTel("");
            user.setEmail("");
            user.setCreated(created);
            user.setTel("");
            int j = userMapper.addUser(user);
            Long id = user.getId();
            User result = new User(id, uuid, username, avatar, user.getEmail(), user.getStatus(), created, "", "");
            System.out.println(result);
            if (j == 0) {
                return Result.fail("登录失败");
            }
            return Result.success(result);
        } else {
            return Result.fail("登录失败");
        }
    }

    public JSONObject toJson(String code) {
        // 小程序唯一标识 (在微信小程序管理后台获取)
        String wxspAppid = "wx41df3076f5aec307";
        // 小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "b5b43f81d3b0968b29588d90646eb331";
        // 授权（必填）
        String grant_type = "authorization_code";

        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
//        String code = "073dSt000vXXDP1D7O3009yZA91dSt0q";
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?"+params;
        String s = HttpUtil.get(url);
        JSONObject json = null;
        try {
            json = new JSONObject(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }
}
